程式碼盡量只寫要說明的地方,無關的就不贅述。
(3-4)頁面表單提交的規範
(3-5)頁面上面區塊(口袋餐廳表單)
該區塊的操作情境請參考之前的「Day25-試試Vue3-規劃餐廳實評的頁面」篇。
點選任一張卡片觸發 selectCard(item) 函式
<textarea></textarea> 加上 v-model="selectCardList.cardComment" 可以將會員輸入的評論作為內容值,去變更 data 裡的屬性 electCardList.cardComment 。當表單按鈕「提交評論」被操作時,會觸發方法裡的 submitComment() 函式
event.preventDefault(); 處理。<template>
  <div class="container">
    ...
    <section class="row mb-4">
      <div class="col-4">
        <h1>餐廳實評</h1>
        <img
          src="https://plus.unsplash.com/premium_photo-1671493286864-f354f3d2feb5?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1974&q=80"
          alt="關於喜愛的圖"
          class="img-fluid"
        />
      </div>
      <div class="col"></div>
      <div class="col-4 mt-5">
        <form>
          <div class="row g-2 mb-4">
            <label for="type" class="col-sm-3 col-form-label">品牌受眾</label>
            <input
              type="text"
              id="type"
              class="form-control col-sm"
              :placeholder="selectCardList.cardType"
              disabled
            />
          </div>
          <div class="row g-2 mb-4">
            <label for="res-name" class="col-sm-3 col-form-label"
              >品牌名稱</label>
            <input
              type="text"
              id="res-name"
              class="form-control col-sm"
              :placeholder="selectCardList.cardBrandName"
              disabled
            />
          </div>
          <div class="row g-2 mb-4">
            <label for="address" class="col-sm-3 col-form-label">地址</label>
            <input
              type="text"
              id="address"
              class="form-control col-sm"
              :placeholder="selectCardList.cardAddress"
              disabled
            />
          </div>
          <div class="row g-2 mb-4">
            <label
              for="exampleFormControlTextarea1"
              class="col-sm-3 col-form-label"
              >餐廳評論</label>
            <textarea
              class="form-control col-sm"
              id="exampleFormControlTextarea1"
              rows="6"
              :disabled="commentDisabled"
              v-model="selectCardList.cardComment"
            ></textarea>
          </div>
          <div class="d-flex justify-content-end">
            <button
              class="btn btn-lg btn-primary mb-4"
              type="submit"
              @click="submitComment()">
              提交評論
            </button>
          </div>
        </form>
      </div>
    </section>
    ...
  </div>
</template>
<script>
import axios from "axios";
import { mapState } from "pinia";
// 定義好的 store 賦值給變數 useLoginStore
// 在元件中引入並呼叫 useLoginStore() 來訪問 store
import { useLoginStore } from "../../components/LoginStore.js";
export default {
  data() {
    return {
      userResList: [],
      selectCardList: {
        cardBrandName: "",
        cardType: "",
        cardAddress: "",
        cardComment: "",
      },
      commentDisabled: true,
      apiUserResUrl: "",
      apiUserResIdUrl: "",
    };
  },
  methods: {
    userPocket() {
      axios
        .get(this.apiUserResUrl)
        .then((res) => {
          console.log(res);
          this.userResList = res.data[0].userRestaurants;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    selectCard(item) {
      ...
    },
    submitComment() {
      event.preventDefault(); // 禁止按鈕提交的默認行為
      // 餐廳評論欄位必須有值才可提交表單
      if (this.selectCardList.cardComment !== "") {
        axios
          .get(this.apiUserResUrl)
          .then((res) => {
            console.log(res);
            // res.data是陣列要變成物件後面才能用push,所以取第一個內容(這裡是物件)
            const userData = res.data[0];
            console.log(userData);
            const dataIndex = userData.userRestaurants.findIndex(
              (dataIndex) =>
                dataIndex.brandName === this.selectCardList.cardBrandName
            );
            console.log(dataIndex);
            userData.userRestaurants[dataIndex]["comment"] =
              this.selectCardList.cardComment;
            axios
              .put(this.apiUserResIdUrl, userData)
              .then((res) => {
                console.log(res);
                alert("該餐廳評論已更新");
                this.userPocket();
              })
              .catch((error) => {
                console.log(error);
                alert("餐廳評論更新失敗");
              });
          })
          .catch((error) => {
            console.log(error);
            alert("無法更新到會員口袋餐廳裡,請洽網站管理員!");
          })
          .finally(() => {
            // 不論請求成功或失敗都会執行
            this.selectCardList.cardBrandName = "";
            this.selectCardList.cardType = "";
            this.selectCardList.cardAddress = "";
            this.selectCardList.cardComment = "";
            // 表單提交後讓關閉對餐廳評論的操作
            this.commentDisabled = true;
          });
      } else {
        alert("餐廳評欄位不可空值!");
      }
    },
  },
  created() {
    this.apiUserResUrl = `http://localhost:3002/userRes?email=${this.userEmail}`;
    this.apiUserResIdUrl = `http://localhost:3002/userRes/${this.userId}`;
  },
  mounted() {
    this.userPocket();
  },
  // 監聽data
  computed: {
    ...mapState(useLoginStore, {
      // 'name' 是 store 中的狀態名,'userName' 是在組件中的名稱
      userName: (state) => state.name,
      userEmail: (state) => state.email,
      userId: (state) => state.id,
    }),
  },
};
</script>